import { createRouter, createWebHistory } from 'vue-router'
import store from '../store'
import Login from '@/pages/login/login.vue'
import Register from '@/pages/login/register.vue'
import ForgotPassword from '@/pages/login/forgotPassword.vue'
import ModifyPassword from '@/pages/login/modifyPassword.vue'
import Main from '@/pages/main.vue'
import Shopping from '@/pages/shopping/index.vue'
import Detail from '@/pages/shopping/detail.vue'
import Cart from '@/pages/cart/index.vue'
import CreateOrder from '@/pages/cart/createOrder.vue'
import Order from '@/pages/order/index.vue'
import FinishOrder from '@/pages/order/finishOrder.vue'
import Personal from '@/pages/personal/index.vue'
import PersonalInfo from '@/pages/personal/personalInfo.vue'
import Station from '@/pages/personal/station.vue'

const routes = [
  {
    path: '/login',
    component: Login,
    meta: { isAuth: false },
  },
  {
    path: '/register',
    component: Register,
    meta: { isAuth: false },
  },
  {
    path: '/forgotPassword',
    component: ForgotPassword,
    meta: { isAuth: false },
  },
  {
    path: "/",
    redirect: "/shopping",
    component: Main,
    children: [
      {
        path: '/shopping',
        component: Shopping,
      },
      {
        path: '/detail',
        component: Detail
      },
      {
        path: '/cart',
        component: Cart,
      },
      {
        path: '/createOrder',
        component: CreateOrder,
      },
      {
        path: '/order',
        component: Order,
      },
      {
        path: '/finishOrder',
        component: FinishOrder,
      },
      {
        path: '/personal',
        component: Personal
      },
      {
        path: '/personalInfo',
        component: PersonalInfo
      },
      {
        path: '/modifyPassword',
        component: ModifyPassword
      },
      {
        path: '/station',
        component: Station
      },
    ]
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});
router.beforeEach(async (to, from, next) => {
  if(to.meta.isAuth === false) {
    next();
  }
  if (!localStorage.userId) {
    next('/login')
  } else {
    if (!store.state.personal) {
      const data = await post('/detail/member', { id: localStorage.userId });
      if (!data) {
        return next('/login')
      }
      store.commit('setPersonal', data.result);
    }
    next();
  }
});

export default router
